package utils;

import book.Book;
import com.bit.utils.FileUtils;

import java.time.LocalDate;

import static constant.Constant.ALL_BOOK_FILE_NAME;

public class AnalyzingBook {
    public AnalyzingBook() {}
    public Book[] loadObject(String fileName) {
        String content = FileUtils.readFile(fileName);
        if(content.isEmpty()){
            System.out.println("file content is emptyC"+fileName);
            return null;
        }
        String[] lines = content.split("\n");
        Book[] books = new Book[lines.length];
        for(int i = 0; i < lines.length; i++){
            books[i]=parseBookJson(lines[i]);
        }
        return books;
    }

    public void storeObject(Book[] books, String fileName){
        int realBookCount = 0;
        for (int i = 0; i < books.length; i++) {
            if(books[i]!=null){
                realBookCount++;
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (int j = 0; j < realBookCount; j++) {
            stringBuilder.append(books[j].toJson());
            if(j!=realBookCount-1){
                stringBuilder.append("\n");
            }
        }

        FileUtils.writeFile(stringBuilder.toString(),fileName);
    }

    private Book parseBookJson(String bookJson){
    if(bookJson==null||bookJson.isEmpty()){
        return null;
    }
    String[] lines = bookJson.split(",");
    int bookId = Integer.parseInt(lines[0]);
    String bookName=lines[1];
    String author=lines[2];
    String category=lines[3];
    int publishYear=Integer.parseInt(lines[4]);
    boolean isBorrowed=Boolean.parseBoolean(lines[5]);
    int borrowCount=Integer.parseInt(lines[6]);
    LocalDate shelfDate=LocalDate.parse(lines[7]);

    if(bookName!=null&&author!=null&&category!=null&&shelfDate!=null){
        Book book=new Book(bookName,author,category,publishYear,shelfDate);
        book.setBookId(bookId);
        book.setBorrowed(isBorrowed);
        book.setBorrowCount(borrowCount);
        return book;
    }
    return null;
    }

    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("java", "gaobo", " 编程 ", 1994, LocalDate.of(2023, 9, 24));
        books[1] = new Book("mysql", "lisi", " 编程 ", 1999, LocalDate.of(2024, 2, 10));
        books[2] = new Book("php", "gaobo", " 编程 ", 2020, LocalDate.of(2023, 9, 23));
        AnalyzingBook analyzingBook = new AnalyzingBook();
        analyzingBook.storeObject(books, ALL_BOOK_FILE_NAME);


        books=analyzingBook.loadObject(ALL_BOOK_FILE_NAME);

        for (int i = 0; i < books.length; i++) {
            System.out.println(books[i].toString());
        }
    }
}
